import 'package:flutter/material.dart';
import 'package:file_picker/file_picker.dart';
import 'package:image_picker/image_picker.dart';
import '../AI/tina_dart/BaseAPI.dart';
import '../serve/file_serve.dart';
import '../AI/dify_datasets.dart';
import '../AI/screen_shot_serve.dart';
import '../serve/upload_service.dart';
import '../AI/smart_floating_ball_service.dart';

class UploadPage extends StatefulWidget {
  final BaseAPI llm;  
  final FileServe fileServe;
  final DifyKnowledgeDatabase difyKnowledge;
  final String appDataDir;
  final ScreenShotServe? screenShotServe;
  final String? preSelectedImagePath; // 预选的图片路径（来自悬浮球截图）

  const UploadPage({
    Key? key,
    required this.llm,
    required this.fileServe,
    required this.difyKnowledge,
    required this.appDataDir,
    this.screenShotServe,
    this.preSelectedImagePath,
  }) : super(key: key);

  @override
  _UploadPageState createState() => _UploadPageState();
}

class _UploadPageState extends State<UploadPage> {
  final ImagePicker _imagePicker = ImagePicker();
  final UploadService _uploadService = UploadService();
  bool _isProcessing = false;
  bool _disposed = false;
  bool _isFloatingBallEnabled = false; // 悬浮球状态
  
  // 静态变量跟踪已处理的图片，避免重复处理
  static final Set<String> _processedImages = <String>{};

  @override
  void initState() {
    super.initState();
    // 初始化上传服务
    _uploadService.initialize(
      llm: widget.llm,
      fileServe: widget.fileServe,
      difyKnowledge: widget.difyKnowledge,
      appDataDir: widget.appDataDir,
      screenShotServe: widget.screenShotServe,
    );
    // 监听上传服务状态变化
    _uploadService.addListener(_onUploadServiceChanged);
    
    // 初始化悬浮球服务状态
    _initFloatingBallStatus();
    
    // 如果有预选图片路径，自动开始处理
    if (widget.preSelectedImagePath != null) {
      print('UploadPage: 检测到预选图片，开始自动处理: ${widget.preSelectedImagePath}');
      WidgetsBinding.instance.addPostFrameCallback((_) {
        _processPreSelectedImage();
      });
    }
  }

  @override
  void dispose() {
    _disposed = true;
    _uploadService.removeListener(_onUploadServiceChanged);
    
    // 清理已处理的图片记录（如果是当前页面处理的）
    if (widget.preSelectedImagePath != null) {
      _processedImages.remove(widget.preSelectedImagePath);
    }
    
    super.dispose();
  }

  void _onUploadServiceChanged() {
    // 使用双重检查确保安全
    if (!_disposed && mounted) {
      try {
      setState(() {
        // 更新UI状态
        _isProcessing = _uploadService.activeTasksCount > 0;
      });
      } catch (e) {
        // 忽略在销毁过程中的setState错误
        print('UploadPage: setState错误已忽略 - $e');
      }
    }
  }

  /// 初始化悬浮球状态
  Future<void> _initFloatingBallStatus() async {
    try {
      final isRunning = await SmartFloatingBallService.isServiceRunning();
      if (mounted) {
        setState(() {
          _isFloatingBallEnabled = isRunning;
        });
      }
    } catch (e) {
      print('获取悬浮球状态失败: $e');
    }
  }

  /// 切换悬浮球状态
  Future<void> _toggleFloatingBall() async {
    try {
      bool success = false;
      
      if (_isFloatingBallEnabled) {
        // 停止悬浮球服务
        success = await SmartFloatingBallService.stopService();
        if (success && mounted) {
          setState(() {
            _isFloatingBallEnabled = false;
          });
          _showFloatingBallMessage('智能悬浮球已关闭');
        }
      } else {
        // 启动悬浮球服务
        success = await SmartFloatingBallService.startService();
        if (success) {
          // 启动成功后初始化持久截屏
          await SmartFloatingBallService.initializePersistentCapture();
          if (mounted) {
            setState(() {
              _isFloatingBallEnabled = true;
            });
            _showFloatingBallMessage('智能悬浮球已启动，点击即可快速截图');
          }
        }
      }
      
      if (!success && mounted) {
        _showFloatingBallMessage(
          _isFloatingBallEnabled ? '关闭悬浮球失败' : '启动悬浮球失败，请检查悬浮窗权限', 
          isError: true
        );
      }
    } catch (e) {
      print('切换悬浮球状态失败: $e');
      if (mounted) {
        _showFloatingBallMessage('操作失败: $e', isError: true);
      }
    }
  }

  /// 显示悬浮球消息
  void _showFloatingBallMessage(String message, {bool isError = false}) {
    if (!mounted) return;
    
    ScaffoldMessenger.of(context).showSnackBar(
      SnackBar(
        content: Row(
          children: [
            Icon(
              isError ? Icons.error_outline : Icons.smart_toy,
              color: Colors.white,
              size: 20,
            ),
            SizedBox(width: 8),
            Expanded(
              child: Text(
                message,
                style: TextStyle(
                  color: Colors.white,
                  fontWeight: FontWeight.w500,
                ),
              ),
            ),
          ],
        ),
        backgroundColor: isError ? Colors.red[600] : Colors.green[600],
        behavior: SnackBarBehavior.floating,
        shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(12)),
        duration: Duration(seconds: 3),
      ),
    );
  }

  /// 处理预选图片（来自悬浮球截图）
  Future<void> _processPreSelectedImage() async {
    if (widget.preSelectedImagePath == null) return;
    
    try {
      print('UploadPage: 开始处理预选图片: ${widget.preSelectedImagePath}');
      
      // 检查是否已经处理过这个图片
      if (_processedImages.contains(widget.preSelectedImagePath)) {
        print('UploadPage: 预选图片已处理过，跳过重复处理');
        return;
      }
      
      // 检查是否已经存在相同路径的任务，避免重复添加
      final existingTask = _uploadService.uploadTasks.any((task) => 
        task.filePath == widget.preSelectedImagePath
      );
      
      if (existingTask) {
        print('UploadPage: 预选图片已存在于上传队列中，跳过重复添加');
        return;
      }
      
      // 标记为已处理
      _processedImages.add(widget.preSelectedImagePath!);
      
      // 直接添加到上传队列，标记为悬浮球截图
      _uploadService.addImageUploadTask(widget.preSelectedImagePath!, 'floating_ball_screenshot');
      
      if (mounted) {
        ScaffoldMessenger.of(context).showSnackBar(
          SnackBar(
            content: Row(
              children: [
                Icon(Icons.smart_toy, color: Colors.white),
                SizedBox(width: 8),
                Text('悬浮球截图已添加到上传队列'),
              ],
            ),
            backgroundColor: Colors.green[600],
            behavior: SnackBarBehavior.floating,
            shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(12)),
          ),
        );
      }
    } catch (e) {
      print('UploadPage: 处理预选图片失败 - $e');
      if (mounted) {
        ScaffoldMessenger.of(context).showSnackBar(
          SnackBar(
            content: Row(
              children: [
                Icon(Icons.error, color: Colors.white),
                SizedBox(width: 8),
                Expanded(child: Text('处理悬浮球截图失败: $e')),
              ],
            ),
            backgroundColor: Colors.red[600],
            behavior: SnackBarBehavior.floating,
            shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(12)),
          ),
        );
      }
    }
  }

  @override
  Widget build(BuildContext context) {
    return WillPopScope(
      onWillPop: () async {
        if (!_disposed && mounted) {
        Navigator.pop(context, _uploadService.hasSuccessfulUploads());
        }
        return false;
      },
      child: Scaffold(
        backgroundColor: Colors.grey[50],
        body: Column(
          children: [
            // 美化的顶部区域
            _buildBeautifulHeader(),
            // 内容区域
            Expanded(
              child: Column(
                children: [
                  // 上传选项区域
                  _buildUploadOptionsSection(),
                  // 上传任务列表
                  Expanded(
                    child: _uploadService.uploadTasks.isEmpty
                        ? _buildEmptyState()
                        : _buildUploadTaskList(),
                  ),
                ],
              ),
            ),
          ],
        ),
      ),
    );
  }

  Widget _buildBeautifulHeader() {
    return Container(
      decoration: BoxDecoration(
        gradient: LinearGradient(
          begin: Alignment.topLeft,
          end: Alignment.bottomRight,
          colors: [
            Color(0xFF667eea),
            Color(0xFF764ba2),
          ],
        ),
        borderRadius: BorderRadius.only(
          bottomLeft: Radius.circular(32),
          bottomRight: Radius.circular(32),
        ),
        boxShadow: [
          BoxShadow(
            color: Colors.black.withOpacity(0.1),
            blurRadius: 20,
            offset: Offset(0, 10),
          ),
        ],
      ),
      child: SafeArea(
        child: Padding(
          padding: EdgeInsets.fromLTRB(24, 12, 24, 24),
          child: Column(
            children: [
              // 顶部导航栏
              Row(
                children: [
                  // 返回按钮
                  Container(
                    decoration: BoxDecoration(
                      color: Colors.white.withOpacity(0.2),
                      borderRadius: BorderRadius.circular(12),
                    ),
                    child: IconButton(
                      icon: Icon(Icons.arrow_back, color: Colors.white),
                      onPressed: () {
                        if (!_disposed && mounted) {
                          Navigator.pop(context, _uploadService.hasSuccessfulUploads());
                        }
                      },
                    ),
                  ),
                  
                  SizedBox(width: 16),
                  
                  // 标题和图标
                  Container(
                    padding: EdgeInsets.all(12),
                    decoration: BoxDecoration(
                      color: Colors.white.withOpacity(0.2),
                      borderRadius: BorderRadius.circular(16),
                    ),
                    child: Icon(
                      Icons.cloud_upload_rounded,
                      color: Colors.white,
                      size: 24,
                    ),
                  ),
                  
                  SizedBox(width: 16),
                  
                  Expanded(
                    child: Column(
                      crossAxisAlignment: CrossAxisAlignment.start,
                      children: [
                        Text(
                          '文件上传',
                          style: TextStyle(
                            fontSize: 24,
                            fontWeight: FontWeight.w700,
                            color: Colors.white,
                            letterSpacing: 0.5,
                          ),
                        ),
                        SizedBox(height: 4),
                        Text(
                          '上传文档到知识库',
                          style: TextStyle(
                            fontSize: 14,
                            color: Colors.white.withOpacity(0.8),
                            fontWeight: FontWeight.w500,
                          ),
                        ),
                      ],
                    ),
                  ),

                  
                  // 清理按钮
                  if (_uploadService.uploadTasks.isNotEmpty)
                    Container(
                      decoration: BoxDecoration(
                        color: Colors.white.withOpacity(0.2),
                        borderRadius: BorderRadius.circular(12),
                      ),
                      child: IconButton(
                        icon: Icon(Icons.clear_all, color: Colors.white),
                        tooltip: '清理已完成',
                        onPressed: () {
                          if (!_disposed && mounted) {
                            _uploadService.clearCompletedTasks();
                          }
                        },
                      ),
                    ),
                ],
              ),
              
              SizedBox(height: 20),
              
              // 统计信息
              Container(
                padding: EdgeInsets.symmetric(horizontal: 20, vertical: 12),
                decoration: BoxDecoration(
                  color: Colors.white.withOpacity(0.15),
                  borderRadius: BorderRadius.circular(20),
                  border: Border.all(color: Colors.white.withOpacity(0.2)),
                ),
                child: Row(
                  mainAxisAlignment: MainAxisAlignment.spaceAround,
                  children: [
                    _buildStatItem(
                      '总任务', 
                      '${_uploadService.uploadTasks.length}', 
                      Icons.list_alt
                    ),
                    Container(height: 20, width: 1, color: Colors.white.withOpacity(0.3)),
                    _buildStatItem(
                      '进行中', 
                      '${_uploadService.activeTasksCount}', 
                      Icons.upload
                    ),
                    Container(height: 20, width: 1, color: Colors.white.withOpacity(0.3)),
                    _buildStatItem(
                      '已完成', 
                      '${_uploadService.uploadTasks.where((task) => task.status == UploadStatus.success).length}', 
                      Icons.check_circle
              ),
          ],
        ),
              ),
          ],
        ),
        ),
      ),
    );
  }

  Widget _buildStatItem(String label, String value, IconData icon) {
    return Row(
      mainAxisSize: MainAxisSize.min,
          children: [
        Icon(icon, color: Colors.white, size: 16),
        SizedBox(width: 6),
        Column(
          children: [
            Text(
              value,
              style: TextStyle(
                color: Colors.white,
                fontSize: 14,
                fontWeight: FontWeight.w700,
              ),
            ),
            Text(
              label,
              style: TextStyle(
                color: Colors.white.withOpacity(0.8),
                fontSize: 11,
                fontWeight: FontWeight.w500,
              ),
            ),
          ],
        ),
      ],
    );
  }

  Widget _buildUploadOptionsSection() {
    return Container(
      padding: EdgeInsets.all(24),
              child: Column(
                crossAxisAlignment: CrossAxisAlignment.start,
                children: [
                  // 标题和悬浮球开关
                  Row(
                    mainAxisAlignment: MainAxisAlignment.spaceBetween,
                    children: [
                      Expanded(
                        child: Column(
                          crossAxisAlignment: CrossAxisAlignment.start,
                          children: [
                            Text(
                              '选择上传方式',
                              style: TextStyle(
                                fontSize: 20,
                                fontWeight: FontWeight.w700,
                                color: Colors.grey[800],
                                letterSpacing: 0.5,
                              ),
                            ),
                            SizedBox(height: 8),
                            Text(
                              '支持多种文件格式，自动识别分类',
                              style: TextStyle(
                                fontSize: 14,
                                color: Colors.grey[600],
                                fontWeight: FontWeight.w500,
                              ),
                            ),
                          ],
                        ),
                      ),
                      // 悬浮球开关按钮
                      Container(
                        decoration: BoxDecoration(
                          color: _isFloatingBallEnabled 
                              ? Colors.green.withOpacity(0.2) 
                              : Colors.grey.withOpacity(0.15),
                          borderRadius: BorderRadius.circular(20),
                          border: Border.all(
                            color: _isFloatingBallEnabled 
                                ? Colors.green.withOpacity(0.5)
                                : Colors.grey.withOpacity(0.3),
                            width: 1,
                          ),
                        ),
                        child: Material(
                          color: Colors.transparent,
                          child: InkWell(
                            borderRadius: BorderRadius.circular(20),
                            onTap: _toggleFloatingBall,
                            child: Padding(
                              padding: EdgeInsets.symmetric(horizontal: 12, vertical: 8),
                              child: Row(
                                mainAxisSize: MainAxisSize.min,
                                children: [
                                  Icon(
                                    _isFloatingBallEnabled 
                                        ? Icons.smart_toy 
                                        : Icons.smart_toy_outlined,
                                    color: _isFloatingBallEnabled 
                                        ? Colors.green[600] 
                                        : Colors.grey[600],
                                    size: 16,
                                  ),
                                  SizedBox(width: 6),
                                  Text(
                                    _isFloatingBallEnabled ? '悬浮球' : '启动',
                                    style: TextStyle(
                                      color: _isFloatingBallEnabled 
                                          ? Colors.green[600] 
                                          : Colors.grey[600],
                                      fontSize: 12,
                                      fontWeight: FontWeight.w600,
                                    ),
                                  ),
                                ],
                              ),
                            ),
                          ),
                        ),
                      ),
                    ],
                  ),
          SizedBox(height: 20),
                  Row(
                    children: [
                      Expanded(
                        child: _buildUploadOption(
                  icon: Icons.description_rounded,
                          title: '上传文档',
                          subtitle: 'PDF、TXT、MD、DOCX',
                  color: Color(0xFF4CAF50),
                          onTap: _pickAndUploadFile,
                        ),
                      ),
              SizedBox(width: 16),
                      Expanded(
                        child: _buildUploadOption(
                  icon: Icons.image_rounded,
                          title: '上传图片',
                          subtitle: 'OCR识别文本',
                  color: Color(0xFF2196F3),
                          onTap: _pickAndProcessImage,
                        ),
                      ),
              SizedBox(width: 16),
                      Expanded(
                        child: _buildUploadOption(
                  icon: Icons.camera_alt_rounded,
                          title: '拍摄照片',
                          subtitle: '拍照识别文本',
                  color: Color(0xFF9C27B0),
                          onTap: _takeAndProcessPhoto,
                        ),
                      ),
                    ],
                  ),
                ],
      ),
    );
  }

  Widget _buildUploadOption({
    required IconData icon,
    required String title,
    required String subtitle,
    required Color color,
    required VoidCallback onTap,
  }) {
    return Container(
      decoration: BoxDecoration(
        color: Colors.white,
        borderRadius: BorderRadius.circular(20),
        boxShadow: [
          BoxShadow(
            color: Colors.black.withOpacity(0.08),
            blurRadius: 16,
            offset: Offset(0, 8),
          ),
        ],
      ),
      child: Material(
        color: Colors.transparent,
      child: InkWell(
        onTap: onTap,
          borderRadius: BorderRadius.circular(20),
        child: Padding(
            padding: EdgeInsets.all(20),
          child: Column(
            children: [
                Container(
                  width: 60,
                  height: 60,
                  decoration: BoxDecoration(
                    gradient: LinearGradient(
                      colors: [
                        color.withOpacity(0.1),
                        color.withOpacity(0.2),
                      ],
                    ),
                    borderRadius: BorderRadius.circular(20),
                  ),
                  child: Center(
                    child: Icon(
                icon,
                size: 32,
                      color: color,
              ),
                  ),
              ),
                SizedBox(height: 16),
              Text(
                title,
                style: TextStyle(
                    fontWeight: FontWeight.w700,
                    fontSize: 16,
                    color: Colors.grey[800],
                    letterSpacing: 0.3,
                ),
                textAlign: TextAlign.center,
              ),
                SizedBox(height: 6),
              Text(
                subtitle,
                style: TextStyle(
                  fontSize: 12,
                  color: Colors.grey[600],
                    fontWeight: FontWeight.w500,
                ),
                textAlign: TextAlign.center,
              ),
            ],
            ),
          ),
        ),
      ),
    );
  }

  Widget _buildEmptyState() {
    return Container(
      padding: EdgeInsets.all(32),
      child: Center(
      child: Column(
        mainAxisAlignment: MainAxisAlignment.center,
        children: [
            Container(
              width: 120,
              height: 120,
              decoration: BoxDecoration(
                gradient: LinearGradient(
                  colors: [Color(0xFF667eea), Color(0xFF764ba2)],
                ),
                shape: BoxShape.circle,
                boxShadow: [
                  BoxShadow(
                    color: Color(0xFF667eea).withOpacity(0.3),
                    blurRadius: 30,
                    offset: Offset(0, 15),
                  ),
                ],
              ),
              child: Container(
                margin: EdgeInsets.all(8),
                decoration: BoxDecoration(
                  shape: BoxShape.circle,
                  color: Colors.white,
                ),
                child: Center(
                  child: Icon(
                    Icons.cloud_upload_rounded,
                    size: 48,
                    color: Color(0xFF667eea),
                  ),
                ),
              ),
          ),
            SizedBox(height: 32),
          Text(
            '还没有上传任务',
            style: TextStyle(
                fontSize: 20,
                fontWeight: FontWeight.w700,
                color: Colors.grey[800],
                letterSpacing: 0.5,
            ),
          ),
          SizedBox(height: 8),
            Container(
              padding: EdgeInsets.symmetric(horizontal: 24, vertical: 8),
              decoration: BoxDecoration(
                gradient: LinearGradient(
                  colors: [Color(0xFF667eea).withOpacity(0.1), Color(0xFF764ba2).withOpacity(0.1)],
                ),
                borderRadius: BorderRadius.circular(20),
              ),
              child: Text(
            '选择上方的上传方式开始上传文件',
            style: TextStyle(
              fontSize: 14,
                  color: Colors.grey[600],
                  fontWeight: FontWeight.w500,
                ),
            ),
          ),
        ],
          ),
      ),
    );
  }

  Widget _buildUploadTaskList() {
    return ListView.builder(
      padding: EdgeInsets.all(24),
      itemCount: _uploadService.uploadTasks.length,
      itemBuilder: (context, index) {
        final task = _uploadService.uploadTasks[index];
        return _buildUploadTaskCard(task);
      },
    );
  }

  Widget _buildUploadTaskCard(UploadTask task) {
    return Container(
      margin: EdgeInsets.only(bottom: 16),
      decoration: BoxDecoration(
        color: Colors.white,
        borderRadius: BorderRadius.circular(20),
        boxShadow: [
          BoxShadow(
            color: Colors.black.withOpacity(0.08),
            blurRadius: 16,
            offset: Offset(0, 8),
          ),
        ],
      ),
      child: Padding(
        padding: EdgeInsets.all(20),
        child: Column(
          crossAxisAlignment: CrossAxisAlignment.start,
          children: [
            Row(
              children: [
                _buildTaskStatusIcon(task.status),
                SizedBox(width: 12),
                Expanded(
                  child: Column(
                    crossAxisAlignment: CrossAxisAlignment.start,
                    children: [
                      Text(
                        task.effectiveFileName,
                        style: TextStyle(
                          fontWeight: FontWeight.w700,
                          fontSize: 16,
                          color: Colors.grey[800],
                          letterSpacing: 0.3,
                        ),
                        maxLines: 1,
                        overflow: TextOverflow.ellipsis,
                      ),
                      SizedBox(height: 6),
                      Container(
                        padding: EdgeInsets.symmetric(horizontal: 8, vertical: 4),
                        decoration: BoxDecoration(
                          gradient: LinearGradient(
                            colors: [Color(0xFF667eea).withOpacity(0.1), Color(0xFF764ba2).withOpacity(0.1)],
                          ),
                          borderRadius: BorderRadius.circular(12),
                        ),
                        child: Text(
                        _getTaskTypeText(task.type),
                        style: TextStyle(
                          fontSize: 12,
                            color: Color(0xFF667eea),
                            fontWeight: FontWeight.w600,
                          ),
                        ),
                      ),
                    ],
                  ),
                ),
                _buildTaskStatusText(task),
              ],
            ),
            SizedBox(height: 16),
            // 进度条
            if (task.status == UploadStatus.uploading)
              Column(
                children: [
                  Container(
                    height: 6,
                    decoration: BoxDecoration(
                      borderRadius: BorderRadius.circular(3),
                      color: Colors.grey[200],
                    ),
                    child: LinearProgressIndicator(
                    value: task.progress,
                      backgroundColor: Colors.transparent,
                    valueColor: AlwaysStoppedAnimation<Color>(
                        Color(0xFF667eea),
                    ),
                      borderRadius: BorderRadius.circular(3),
                  ),
                  ),
                  SizedBox(height: 12),
                  Row(
                    mainAxisAlignment: MainAxisAlignment.spaceBetween,
                    children: [
                      Text(
                        '${(task.progress * 100).toInt()}%',
                        style: TextStyle(
                          fontSize: 13,
                          color: Color(0xFF667eea),
                          fontWeight: FontWeight.w600,
                        ),
                      ),
                      if (task.category != null)
                        Container(
                          padding: EdgeInsets.symmetric(horizontal: 8, vertical: 4),
                          decoration: BoxDecoration(
                            gradient: LinearGradient(
                              colors: [Color(0xFF2196F3).withOpacity(0.1), Color(0xFF21CBF3).withOpacity(0.1)],
                            ),
                            borderRadius: BorderRadius.circular(12),
                          ),
                          child: Text(
                          task.category!,
                          style: TextStyle(
                            fontSize: 12,
                              color: Color(0xFF2196F3),
                              fontWeight: FontWeight.w600,
                            ),
                          ),
                        ),
                    ],
                  ),
                ],
              ),
            // 成功状态显示分类
            if (task.status == UploadStatus.success && task.category != null)
              Container(
                padding: EdgeInsets.symmetric(horizontal: 12, vertical: 8),
                decoration: BoxDecoration(
                  gradient: LinearGradient(
                    colors: [Color(0xFF4CAF50).withOpacity(0.1), Color(0xFF8BC34A).withOpacity(0.1)],
                  ),
                  borderRadius: BorderRadius.circular(12),
                  border: Border.all(color: Color(0xFF4CAF50).withOpacity(0.3)),
                ),
                child: Row(
                  mainAxisSize: MainAxisSize.min,
                  children: [
                    Icon(Icons.label, size: 16, color: Color(0xFF4CAF50)),
                    SizedBox(width: 6),
                    Text(
                  '分类: ${task.category}',
                  style: TextStyle(
                        fontSize: 13,
                        color: Color(0xFF4CAF50),
                        fontWeight: FontWeight.w600,
                  ),
                  ),
                  ],
                ),
              ),
            // 错误信息
            if (task.status == UploadStatus.failed && task.errorMessage != null)
              Container(
                margin: EdgeInsets.only(top: 8),
                padding: EdgeInsets.all(12),
                decoration: BoxDecoration(
                  gradient: LinearGradient(
                    colors: [Color(0xFFF44336).withOpacity(0.1), Color(0xFFE57373).withOpacity(0.1)],
                  ),
                  borderRadius: BorderRadius.circular(12),
                  border: Border.all(color: Color(0xFFF44336).withOpacity(0.3)),
                ),
                child: Row(
                  children: [
                    Icon(Icons.error_outline, size: 16, color: Color(0xFFF44336)),
                    SizedBox(width: 8),
                    Expanded(
                child: Text(
                  task.errorMessage!,
                  style: TextStyle(
                          fontSize: 13,
                          color: Color(0xFFF44336),
                          fontWeight: FontWeight.w500,
                  ),
                      ),
                  ),
                  ],
                ),
              ),
          ],
        ),
      ),
    );
  }

  Widget _buildTaskStatusIcon(UploadStatus status) {
    switch (status) {
      case UploadStatus.waiting:
        return Container(
          width: 24,
          height: 24,
          decoration: BoxDecoration(
            gradient: LinearGradient(
              colors: [Color(0xFFFF9800).withOpacity(0.1), Color(0xFFFFC107).withOpacity(0.1)],
            ),
            shape: BoxShape.circle,
          ),
          child: Icon(Icons.schedule_rounded, color: Color(0xFFFF9800), size: 16),
        );
      case UploadStatus.uploading:
        return Container(
          width: 24,
          height: 24,
          decoration: BoxDecoration(
            gradient: LinearGradient(
              colors: [Color(0xFF2196F3).withOpacity(0.1), Color(0xFF21CBF3).withOpacity(0.1)],
            ),
            shape: BoxShape.circle,
          ),
          child: Padding(
            padding: EdgeInsets.all(4),
          child: CircularProgressIndicator(
            strokeWidth: 2,
              valueColor: AlwaysStoppedAnimation<Color>(Color(0xFF2196F3)),
            ),
          ),
        );
      case UploadStatus.pendingCategory:
        return Container(
          width: 24,
          height: 24,
          decoration: BoxDecoration(
            gradient: LinearGradient(
              colors: [Color(0xFF9C27B0).withOpacity(0.1), Color(0xFFE91E63).withOpacity(0.1)],
            ),
            shape: BoxShape.circle,
          ),
          child: Icon(Icons.help_outline_rounded, color: Color(0xFF9C27B0), size: 16),
        );
      case UploadStatus.success:
        return Container(
          width: 24,
          height: 24,
          decoration: BoxDecoration(
            gradient: LinearGradient(
              colors: [Color(0xFF4CAF50).withOpacity(0.1), Color(0xFF8BC34A).withOpacity(0.1)],
            ),
            shape: BoxShape.circle,
          ),
          child: Icon(Icons.check_circle_rounded, color: Color(0xFF4CAF50), size: 16),
        );
      case UploadStatus.failed:
        return Container(
          width: 24,
          height: 24,
          decoration: BoxDecoration(
            gradient: LinearGradient(
              colors: [Color(0xFFF44336).withOpacity(0.1), Color(0xFFE57373).withOpacity(0.1)],
            ),
            shape: BoxShape.circle,
          ),
          child: Icon(Icons.error_rounded, color: Color(0xFFF44336), size: 16),
        );
    }
  }

  Widget _buildTaskStatusText(UploadTask task) {
    switch (task.status) {
      case UploadStatus.waiting:
        return Container(
          padding: EdgeInsets.symmetric(horizontal: 8, vertical: 4),
          decoration: BoxDecoration(
            gradient: LinearGradient(
              colors: [Color(0xFFFF9800).withOpacity(0.1), Color(0xFFFFC107).withOpacity(0.1)],
            ),
            borderRadius: BorderRadius.circular(12),
          ),
          child: Text('等待中', style: TextStyle(color: Color(0xFFFF9800), fontSize: 12, fontWeight: FontWeight.w600)),
        );
      case UploadStatus.uploading:
        return Container(
          padding: EdgeInsets.symmetric(horizontal: 8, vertical: 4),
          decoration: BoxDecoration(
            gradient: LinearGradient(
              colors: [Color(0xFF2196F3).withOpacity(0.1), Color(0xFF21CBF3).withOpacity(0.1)],
            ),
            borderRadius: BorderRadius.circular(12),
          ),
          child: Text('上传中', style: TextStyle(color: Color(0xFF2196F3), fontSize: 12, fontWeight: FontWeight.w600)),
        );
      case UploadStatus.pendingCategory:
        return GestureDetector(
          onTap: () => _showCategorySelectionDialog(task),
          child: Container(
            padding: EdgeInsets.symmetric(horizontal: 8, vertical: 4),
            decoration: BoxDecoration(
              gradient: LinearGradient(
                colors: [Color(0xFF9C27B0).withOpacity(0.1), Color(0xFFE91E63).withOpacity(0.1)],
              ),
              borderRadius: BorderRadius.circular(12),
              border: Border.all(color: Color(0xFF9C27B0), width: 1),
            ),
            child: Row(
              mainAxisSize: MainAxisSize.min,
              children: [
                Text('待分类', style: TextStyle(color: Color(0xFF9C27B0), fontSize: 12, fontWeight: FontWeight.w600)),
                SizedBox(width: 4),
                Icon(Icons.touch_app, color: Color(0xFF9C27B0), size: 12),
              ],
            ),
          ),
        );
      case UploadStatus.success:
        return Container(
          padding: EdgeInsets.symmetric(horizontal: 8, vertical: 4),
          decoration: BoxDecoration(
            gradient: LinearGradient(
              colors: [Color(0xFF4CAF50).withOpacity(0.1), Color(0xFF8BC34A).withOpacity(0.1)],
            ),
            borderRadius: BorderRadius.circular(12),
          ),
          child: Text('已完成', style: TextStyle(color: Color(0xFF4CAF50), fontSize: 12, fontWeight: FontWeight.w600)),
        );
      case UploadStatus.failed:
        return Container(
          padding: EdgeInsets.symmetric(horizontal: 8, vertical: 4),
          decoration: BoxDecoration(
            gradient: LinearGradient(
              colors: [Color(0xFFF44336).withOpacity(0.1), Color(0xFFE57373).withOpacity(0.1)],
            ),
            borderRadius: BorderRadius.circular(12),
          ),
          child: Text('失败', style: TextStyle(color: Color(0xFFF44336), fontSize: 12, fontWeight: FontWeight.w600)),
        );
    }
  }

  String _getTaskTypeText(String type) {
    switch (type) {
      case 'document':
        return '文档上传';
      case 'image':
        return '图片识别';
      case 'photo':
        return '拍照识别';
      default:
        return '未知类型';
    }
  }

  // 选择并上传文件
  Future<void> _pickAndUploadFile() async {
    try {
      FilePickerResult? result = await FilePicker.platform.pickFiles(
        type: FileType.custom,
        allowedExtensions: ['pdf', 'txt', 'md', 'docx'],
        allowMultiple: true,
      );

      if (result != null) {
        for (PlatformFile file in result.files) {
          if (file.path != null) {
            _uploadService.addDocumentUploadTask(file.path!);
          }
        }
        
        if (mounted) {
          ScaffoldMessenger.of(context).showSnackBar(
            SnackBar(content: Text('已添加 ${result.files.length} 个文档到上传队列')),
          );
        }
      }
    } catch (e) {
      if (mounted) {
        ScaffoldMessenger.of(context).showSnackBar(
          SnackBar(content: Text('选择文件失败: $e')),
        );
      }
    }
  }

  // 选择并处理图片
  Future<void> _pickAndProcessImage() async {
    try {
      final XFile? imageFile = await _imagePicker.pickImage(
        source: ImageSource.gallery,
        imageQuality: 80,
      );

      if (imageFile != null) {
        _uploadService.addImageUploadTask(imageFile.path, 'image');
        
        if (mounted) {
          ScaffoldMessenger.of(context).showSnackBar(
            SnackBar(content: Text('已添加图片到上传队列')),
          );
        }
      }
    } catch (e) {
      if (mounted) {
        ScaffoldMessenger.of(context).showSnackBar(
          SnackBar(content: Text('选择图片失败: $e')),
        );
      }
    }
  }

  // 拍照并处理照片
  Future<void> _takeAndProcessPhoto() async {
    try {
      final XFile? photoFile = await _imagePicker.pickImage(
        source: ImageSource.camera,
        imageQuality: 80,
      );

      if (photoFile != null) {
        _uploadService.addImageUploadTask(photoFile.path, 'photo');
        
        if (mounted) {
          ScaffoldMessenger.of(context).showSnackBar(
            SnackBar(content: Text('已添加照片到上传队列')),
          );
        }
      }
    } catch (e) {
      if (mounted) {
        ScaffoldMessenger.of(context).showSnackBar(
          SnackBar(content: Text('拍照失败: $e')),
        );
      }
    }
  }

  // 显示分类选择对话框
  Future<void> _showCategorySelectionDialog(UploadTask task) async {
    List<String> categories = [];
    try {
      categories = await widget.fileServe.getCategories();
    } catch (e) {
      categories = ['未分类'];
    }

    String selectedCategory = task.suggestedCategory ?? '未分类';
    String newCategory = '';
    bool useNewCategory = false;

    await showDialog(
      context: context,
      barrierDismissible: false,
      builder: (context) {
        return StatefulBuilder(
          builder: (context, setState) {
            return AlertDialog(
              shape: RoundedRectangleBorder(
                borderRadius: BorderRadius.circular(20),
              ),
              title: Row(
                children: [
                  Container(
                    padding: EdgeInsets.all(8),
                    decoration: BoxDecoration(
                      gradient: LinearGradient(
                        colors: [Color(0xFF9C27B0).withOpacity(0.1), Color(0xFFE91E63).withOpacity(0.1)],
                      ),
                      borderRadius: BorderRadius.circular(12),
                    ),
                    child: Icon(
                      Icons.folder_outlined,
                      color: Color(0xFF9C27B0),
                      size: 24,
                    ),
                  ),
                  SizedBox(width: 12),
                  Expanded(
                    child: Text(
                      '选择文档分类',
                      style: TextStyle(
                        fontSize: 18,
                        fontWeight: FontWeight.w700,
                        color: Colors.grey[800],
                      ),
                    ),
                  ),
                ],
              ),
              content: Container(
                width: double.maxFinite,
                constraints: BoxConstraints(maxHeight: 400),
                child: SingleChildScrollView(
                  child: Column(
                    mainAxisSize: MainAxisSize.min,
                    crossAxisAlignment: CrossAxisAlignment.start,
                    children: [
                      // 文档信息
                      Container(
                        padding: EdgeInsets.all(12),
                        decoration: BoxDecoration(
                          color: Colors.grey[50],
                          borderRadius: BorderRadius.circular(12),
                          border: Border.all(color: Colors.grey[200]!),
                        ),
                        child: Column(
                          crossAxisAlignment: CrossAxisAlignment.start,
                          children: [
                            Text(
                              '文档: ${task.effectiveFileName}',
                              style: TextStyle(
                                fontSize: 14,
                                fontWeight: FontWeight.w600,
                                color: Colors.grey[700],
                              ),
                            ),
                            SizedBox(height: 4),
                            if (task.suggestedCategory != null)
                              Text(
                                'AI建议分类: ${task.suggestedCategory}',
                                style: TextStyle(
                                  fontSize: 13,
                                  color: Color(0xFF9C27B0),
                                  fontWeight: FontWeight.w500,
                                ),
                              ),
                          ],
                        ),
                      ),
                      
                      SizedBox(height: 16),
                      
                      // 现有分类列表
                      if (categories.isNotEmpty) ...[
                        Text(
                          '选择现有分类:',
                          style: TextStyle(
                            fontSize: 16,
                            fontWeight: FontWeight.w600,
                            color: Colors.grey[700],
                          ),
                        ),
                        SizedBox(height: 8),
                        ...categories.map((category) {
                          return Container(
                            margin: EdgeInsets.only(bottom: 4),
                            child: RadioListTile<String>(
                              title: Text(
                                category,
                                style: TextStyle(fontSize: 14),
                              ),
                              value: category,
                              groupValue: useNewCategory ? null : selectedCategory,
                              activeColor: Color(0xFF9C27B0),
                              onChanged: (value) {
                                if (!_disposed && mounted) {
                                  setState(() {
                                    selectedCategory = value!;
                                    useNewCategory = false;
                                  });
                                }
                              },
                            ),
                          );
                        }).toList(),
                        
                        Divider(height: 24),
                      ],
                      
                      // 创建新分类选项
                      RadioListTile<String>(
                        title: Text('创建新分类'),
                        value: 'new',
                        groupValue: useNewCategory ? 'new' : null,
                        activeColor: Color(0xFF9C27B0),
                        onChanged: (value) {
                          if (!_disposed && mounted) {
                            setState(() {
                              useNewCategory = true;
                              newCategory = task.suggestedCategory ?? '';
                            });
                          }
                        },
                      ),
                      if (useNewCategory)
                        Padding(
                          padding: const EdgeInsets.symmetric(horizontal: 16.0),
                          child: TextField(
                            decoration: InputDecoration(
                              labelText: '新分类名称',
                              hintText: '输入分类名称',
                              border: OutlineInputBorder(
                                borderRadius: BorderRadius.circular(12),
                              ),
                              focusedBorder: OutlineInputBorder(
                                borderRadius: BorderRadius.circular(12),
                                borderSide: BorderSide(color: Color(0xFF9C27B0)),
                              ),
                            ),
                            onChanged: (value) {
                              newCategory = value;
                            },
                            controller: TextEditingController(text: task.suggestedCategory ?? ''),
                          ),
                        ),
                    ],
                  ),
                ),
              ),
              actions: [
                Container(
                  height: 44,
                  child: TextButton(
                    onPressed: () {
                      Navigator.pop(context);
                    },
                    style: TextButton.styleFrom(
                      shape: RoundedRectangleBorder(
                        borderRadius: BorderRadius.circular(12),
                      ),
                      backgroundColor: Colors.grey[100],
                    ),
                    child: Text(
                      '取消',
                      style: TextStyle(
                        color: Colors.grey[700],
                        fontWeight: FontWeight.w600,
                        fontSize: 14,
                      ),
                    ),
                  ),
                ),
                SizedBox(width: 8),
                Container(
                  height: 44,
                  child: TextButton(
                    onPressed: () async {
                      String finalCategory;
                      if (useNewCategory && newCategory.isNotEmpty) {
                        finalCategory = newCategory.trim();
                        // 添加新分类到系统
                        try {
                          await widget.fileServe.addCategory(finalCategory);
                        } catch (e) {
                          print('添加新分类失败: $e');
                        }
                      } else {
                        finalCategory = selectedCategory;
                      }
                      
                      Navigator.pop(context);
                      
                      // 确认分类
                      try {
                        await _uploadService.confirmDocumentCategory(task.id, finalCategory);
                        if (!_disposed && mounted) {
                          try {
                            ScaffoldMessenger.of(context).showSnackBar(
                              SnackBar(
                                content: Text('文档已分类到: $finalCategory'),
                                backgroundColor: Color(0xFF4CAF50),
                                behavior: SnackBarBehavior.floating,
                                shape: RoundedRectangleBorder(
                                  borderRadius: BorderRadius.circular(12),
                                ),
                              ),
                            );
                          } catch (e) {
                            print('显示成功SnackBar失败: $e');
                          }
                        }
                      } catch (e) {
                        if (!_disposed && mounted) {
                          try {
                            ScaffoldMessenger.of(context).showSnackBar(
                              SnackBar(
                                content: Text('分类失败: $e'),
                                backgroundColor: Colors.red[400],
                                behavior: SnackBarBehavior.floating,
                                shape: RoundedRectangleBorder(
                                  borderRadius: BorderRadius.circular(12),
                                ),
                              ),
                            );
                          } catch (e) {
                            print('显示错误SnackBar失败: $e');
                          }
                        }
                      }
                    },
                    style: TextButton.styleFrom(
                      shape: RoundedRectangleBorder(
                        borderRadius: BorderRadius.circular(12),
                      ),
                      backgroundColor: Color(0xFF9C27B0),
                    ),
                    child: Text(
                      '确认分类',
                      style: TextStyle(
                        color: Colors.white,
                        fontWeight: FontWeight.w600,
                        fontSize: 14,
                      ),
                    ),
                  ),
                ),
              ],
            );
          },
        );
      },
    );
  }
} 